package com.onpositive.queryeditor.storaging;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;

import com.onpositive.commons.Activator;

public class StorageManager {

	private static StorageManager instance = new StorageManager();

	private HashMap<String, File> urlMapping = new HashMap<String, File>();

	private File root;
	private static String defaultDir = null;

	private StorageManager() {
		defaultDir = WorkspaceLocation.getWorkspaceURL().getFile();
		if (defaultDir != null)
			root = new File(defaultDir, "serviceStorage");
		else
			root = new File(Activator.getDefault().getStateLocation().toFile(),
					"serviceStorage");
		root.mkdirs();
		if (root.exists()) {
			try {
				File file = new File(root + "/storage.cat");
				if (file.exists()) {
					FileInputStream ss = new FileInputStream(file);
					DataInputStream ds = new DataInputStream(ss);
					int readInt = ds.readInt();
					for (int a = 0; a < readInt; a++) {
						String m = ds.readUTF();
						String p = ds.readUTF();
						urlMapping.put(m, new File(p));
					}
				}
			} catch (Exception e) {
				Activator.log(e);
			}
		}
	}

	public File getStorageArea(String url) {
		File file = urlMapping.get(url);
		if (file == null) {
			int mn = 0;
			File ps = null;
			while (true) {
				ps = new File(root, "" + mn);
				if (!urlMapping.containsValue(ps)) {
					break;
				}
				mn++;
			}
			urlMapping.put(url, ps);
			try {
				FileOutputStream ss = new FileOutputStream(root
						+ "/storage.cat");
				DataOutputStream ds = new DataOutputStream(ss);
				try {
					ds.writeInt(urlMapping.size());
					for (String s : urlMapping.keySet()) {
						ds.writeUTF(s);
						ds.writeUTF(urlMapping.get(s).getAbsolutePath());
					}
				} finally {
					ds.close();
				}
			} catch (Exception e) {
				Activator.log(e);
			}
			return ps;
		}
		return file;
	}
	
	public DataInputStream getInputStream(String basePath, String key) throws FileNotFoundException {
		File storageArea = getStorageArea(basePath);
		if (storageArea.exists()) {
			File file = new File(storageArea, key + ".dat");
			if (file.exists())
				return new DataInputStream(new FileInputStream(file));
		}
		return null;
		
	}
	
	public DataOutputStream getOutputStream(String basePath, String key) throws FileNotFoundException {
		File storageArea = getStorageArea(basePath);
		if (!storageArea.exists())
			storageArea.mkdirs();
		if (storageArea.exists()) {
			File file = new File(storageArea, key + ".dat");
			return new DataOutputStream(new FileOutputStream(file));
		}
		return null;
		
	}

	public static StorageManager getInstance() {
		return instance;
	}
}
